package com.lipaluma.field.validator.impl.string;

import java.lang.reflect.Field;
import java.util.Arrays;

import com.lipaluma.annotations.validations.Validate;
import com.lipaluma.context.Context;
import com.lipaluma.field.validator.strategies.SubStringMatcherValidationStrategy;
import com.lipaluma.xml.validator.XmlStartsWithValidator;
import com.lipaluma.xml.validator.XmlValidator;

/**
 * Validator util for String field that check if this value starts with the given value.<br/>
 *  
 * To initialize :
 * <ul>
 * 	<li>
 * 	<u><b>By annotations :</b></u> Use {@link Validate} and use the <code>startsWith</code> attribute to 
 * specify the substring to check.<br/>
 * 	</li>
 * 	<li>
 * 	<u><b>By Xml :</b></u>
 * <ul>
 * <li>
 * To add the startsWith validation, see the example below : <br/>
 * <code>
 * &lt;ToMap field="..." <b>startsWith="test"</b>/><br/>
 * </code>
 * The value of the field must starts with by 'test' in this example.
 * </li>
 * </ul>
 * 
 * @author msoares
 *
 */
public class StringStartsWithValidator extends AbstractSubStringsRequiredValidator {

	public StringStartsWithValidator() {}
	
	public StringStartsWithValidator(String string) {
		super(Arrays.asList(string), SubStringMatcherValidationStrategy.STARTS_WITH, false);
	}

	public boolean init(Context context, Field field) {
		Validate annotation = field.getAnnotation(Validate.class);
		if(annotation == null || annotation.startsWith().isEmpty())
			return false;		
		super.init(Arrays.asList(annotation.startsWith()), SubStringMatcherValidationStrategy.STARTS_WITH, false);
		return true;
	}

	public boolean init(Context context, Field field, XmlValidator xmlValidator) {
		XmlStartsWithValidator validator = (XmlStartsWithValidator) xmlValidator;
		super.init(Arrays.asList(validator.getValue()), SubStringMatcherValidationStrategy.STARTS_WITH, false);
		return true;
	}

}
